package com.eascs.workflow.sys.user;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.util.AssertWarnUtils;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.cookie.CookieSpec;
import com.eascs.web.context.RequestContext;
import com.eascs.web.exception.RedirectException;
import com.eascs.web.p3p.P3pHeader;
import com.eascs.web.sso.SsoUserInterceptor;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.controller.BaseViewController;

@Controller
public class SsoUserViewController extends BaseViewController {
	private static final Logger logger = LoggerFactory.getLogger(SsoUserViewController.class);

	@RequestMapping(value = "/o2o/sso/valid", method = RequestMethod.GET)
	@P3pHeader
	public String valid(ValidForm validForm) {
		AssertWarnUtils.assertNotNull(UserHolder.getUser(), "can't get user from UserHolder");

		// update VailIdCookie
		CookieSpec vailIdCookieSpec = SsoUserInterceptor.buildVailIdCookieSpec();
		vailIdCookieSpec.setValue(RequestContext.getRequestedSessionId());

		// build returnUrl
		String returnUrl = validForm.getReturnUrl();
		String fullServer = UrlUtil.getRequestFullServer(returnUrl);
		if (fullServer.indexOf("eascs.com") < 0) {
			returnUrl = UrlUtil.appendUrl(returnUrl, SsoUserInterceptor.PARAM_VALIDID, vailIdCookieSpec.getValue());
		}

		logger.debug("valid to {}", returnUrl);
		throw new RedirectException(returnUrl);
	}

}
